//
//  EmotionTabBar.m
//  微博2期
//
//  Created by J on 15/12/13.
//
//

#import "EmotionTabBar.h"
#import "EmotionTabBarButton.h"

@interface EmotionTabBar()
@property(nonatomic,weak)UIButton * selectedBtn;
@end
@implementation EmotionTabBar

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        [self setupBtn:@"最近" buttonType:EmotionTabBarButtonTypeRecent];
        [self buttonClick:[self setupBtn:@"默认" buttonType:EmotionTabBarButtonTypeDefault]];//设置选中状态
        [self setupBtn:@"Emoji" buttonType:EmotionTabBarButtonTypeEmoji];
        [self setupBtn:@"浪小花" buttonType:EmotionTabBarButtonTypeLxh];
    }
    
    return self;
    
}

/**
 *  创建一个按钮
 *
 *  @param title 按钮文字
 */
- (UIButton*)setupBtn:(NSString*)title buttonType:(EmotionTabBarButtonType)buttonType{
    
    //创建按钮
    EmotionTabBarButton * button = [EmotionTabBarButton buttonWithType:UIButtonTypeCustom];
    button.tag = buttonType;
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    [button setTitle:title forState:UIControlStateNormal];
    [self addSubview:button];
    
    
    
   
    //设置背景图片
    NSString* image = @"compose_emotion_table_mid_normal";
    NSString* selectedImage = selectedImage = @"compose_emotion_table_mid_selected";

    if (self.subviews.count==1) {
        image = @"compose_emotion_table_left_normal";
        selectedImage = @"compose_emotion_table_left_selected";
        
    }else if (self.subviews.count ==4){
        image = @"compose_emotion_table_right_normal";
        selectedImage = @"compose_emotion_table_right_selected";
    }
//    if (self.subviews.count == 2) {
//        [self buttonClick:button];//设置第二个button选中
//    }
    
    [button setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:selectedImage] forState:UIControlStateDisabled];
    
    
    return button;

    
}

- (void)setDelegate:(id<EmotionTabBarDelegate>)delegate{
    _delegate = delegate;
    [self buttonClick:(UIButton*)[self viewWithTag:EmotionTabBarButtonTypeDefault]];
   
}
//按钮点击
- (void)buttonClick:(UIButton*)button{
    
    self.selectedBtn.enabled = YES;
    button.enabled = NO;
    self.selectedBtn = button;//保存选中按钮
    // 通知代理
    if ([self.delegate respondsToSelector:@selector(emotionTabBar:didSelectButton:)]) {
        [self.delegate emotionTabBar:self didSelectButton:button.tag];
    }
    
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    
    NSUInteger count = self.subviews.count;
    CGFloat btnW = self.width/count;
    for (int i=0; i<count; i++) {
        
        UIButton * btn = self.subviews[i];
        btn.y = 0;
        btn.width = btnW;
        btn.x = i*btnW;
        btn.height = self.height;
    }
    

    
    
}

@end
